// pages/grass/grass.js
var common = require("../../../common/common.js").common;

var util = require("../../../utils/util.js");

var leader = require("../../../common/leader.js").leader;

var customLink = require("../../../common/customLink.js");

var {$author: $author} = require("../../../components/base/authorization.js");

var grassLeftList = [];

//左容器
var grassrighttList = [];

//右容器
const app = getApp();

Page({
    onPageScroll(e) {
        let that = this;
        const query = wx.createSelectorQuery().in(this);
        query.select("#class_list").boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec(function(res) {
            if (res[0]) {
                if (res[0].top <= 80) {
                    that.setData({
                        nav_fixed: "nav_fixed"
                    });
                } else {
                    that.setData({
                        nav_fixed: "nav_normal"
                    });
                }
            }
        });
    },
    /**
   * 页面的初始数据
   */
    data: {
        title: "种草",
        current: 0,
        imgWidth: 0,
        imgHeight: 0,
        grassLeftList: [],
        grassrighttList: [],
        lHeight: 0,
        rHeight: 0,
        ruleModal: false,
        showLoading: 1,
        allBottom: 0,
        //2为加载完  1为加载中  0为还有
        nav_fixed: "nav_normal",
        imgUrls: [],
        //轮播图
        topicList: [],
        grassList: [],
        page: 1,
        pageSize: 10,
        hasMore: true,
        //锁
        tabBar: [],
        myleaderinfo: {
            leader_id: -1,
            leader_id_true: -1
        },
        tabBar1: [ {
            iconName: "icon-shouye1",
            tip: "首页",
            current: 1,
            num: 0,
            url: "/pages/index/index",
            openType: "switchTab"
        }, {
            iconName: "icon-fenlei1",
            tip: "分类",
            current: 0,
            num: 0,
            url: "/pages/classfit/classfit",
            openType: "switchTab"
        }, {
            iconName: "icon-gouwuche2",
            tip: "购物车",
            current: 0,
            num: 0,
            url: "/pages/shopcart/shopcart"
        }, {
            iconName: "icon-dingdan2",
            tip: "订单",
            current: 0,
            num: 0,
            url: "/pages/order/order",
            openType: "switchTab"
        }, {
            iconName: "icon-wode1",
            tip: "我的",
            current: 0,
            num: 0,
            url: "/pages/personal/personal",
            openType: "switchTab"
        } ]
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top
        });
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.getHeader();
        let that = this;
        that.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    imgWidth: res.windowWidth * .48
                });
            }
        });
        that.requestStart();
        common.getBottomIcon(1).then(() => {
            common.getCart();
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: common.throttle(function() {
        let that = this;
        that.requestStart();
        wx.stopPullDownRefresh();
    }, 2e3),
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {
        let that = this;
        that.getNewGrass();
    },
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    requestStart: function() {
        let that = this;
        leader.getMyLeaderInfo_aync();
        that.getBase();
        that.getTopicList();
        //热门话题
                that.getClassification();
        //获取分类
                that.getRotation();
        //首页轮播链接
                that.getTopicList();
        //热门话题
                that.getPlantgrassSet();
        //开启免支付才能上传
                that.getRule();
        //规则
        },
    //全局基础配置信息
    getBase: function(openid) {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    color_header: res.extra.color_header,
                    color_text: res.extra.color_text,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    style: res.extra.style,
                    new_member_audit: res.extra.new_member_audit,
                    userAuditStatus: res.extra.userAuditStatus
                });
            }
        });
    },
    //获取分类
    getClassification: function() {
        let that = this;
        that.setData({
            showLoading: 1,
            chooseTopic: null,
            allBottom: 0,
            grassList: [],
            page: 1
        });
        common.request({
            endpoint: "Plantgrass/manage/grass_cate",
            method: "post",
            data: {},
            success: res => {
                that.setData({
                    class: res.extra,
                    classIndex: 0,
                    chooseClass: res.extra[0].id
                });
                that.getNewGrass();
            }
        });
    },
    //首页轮播链接
    getRotation: function() {
        let that = this;
        common.request({
            endpoint: "Plantgrass/list/rotation",
            method: "post",
            data: {},
            success: res => {
                that.setData({
                    imgUrls: res.extra
                });
            }
        });
    },
    //种草设置
    getPlantgrassSet: function() {
        let that = this;
        common.request({
            endpoint: "Plantgrass/manage/set",
            method: "post",
            success: res => {
                that.setData({
                    plantgrass: res.data
                });
            }
        });
    },
    /**
* 获取规则
*/
    getRule: function() {
        let that = this;
        common.request({
            endpoint: "Plantgrass/person/award_rule",
            method: "post",
            data: {},
            success: res => {
                that.setData({
                    rule: res.extra
                });
            }
        });
    },
    /**
  * 选择图文视频上传 1 图文 2 视频
  */
    gotoUploadPage: function(e) {
        wx.navigateTo({
            url: "/grass/pages/uploadInfo/uploadInfo?type=" + e.currentTarget.dataset.id
        });
    },
    dealTopList: function() {
        let that = this;
        //每4个分一页
                var navTopicList = [];
        let topicListLen = that.data.topicList.length < 8 ? that.data.topicList.length : 8;
        for (let i = 0; i < that.data.topicList.length; i += 4) {
            navTopicList.push(that.data.topicList.slice(i, i + 4));
        }
        that.setData({
            topicList: navTopicList
        });
    },
    /**
   * 获取种草
   */
    getNewGrass: function() {
        let that = this;
        this.setData({
            showLoading: 1,
            allBottom: 0
        });
        common.request({
            endpoint: "Plantgrass/list/list",
            method: "post",
            data: {
                cate_id: that.data.chooseClass,
                topic_id: that.data.chooseTopic,
                page: that.data.page,
                rows: that.data.pageSize
            },
            success: res => {
                if (res.rows.length < 1) {
                    that.setData({
                        allBottom: 2,
                        showLoading: 0,
                        hasMore: true
                    });
                    return;
                }
                let grassList = res.rows;
                grassList.map(x => {
                    if (x.type == 1) {
                        if (!x.img) {
                            x.img = [];
                            x.img.push(that.data.domain + "img/weixin_default.png");
                        } else {
                            x.img = x.img.split(",");
                        }
                    } else {
                        if (!x.cover_img) {
                            x.cover_img = that.data.domain + "img/weixin_default.png";
                        }
                    }
                });
                grassList = that.data.page == 1 ? res.rows : that.data.grassList.concat(res.rows);
                that.setData({
                    grassList: grassList,
                    page: that.data.page + 1,
                    showLoading: 0,
                    hasMore: true
                });
            },
            fail(res) {
                that.setData({
                    hasMore: true
                });
            }
        });
    },
    /**
   * 跳转视频或者图文详情页
   */
    toDetail: function(e) {
        let type = e.currentTarget.dataset.item.type;
        if (type == 1) {
            //图文
            wx.navigateTo({
                url: "/grass/pages/grassDetail/grassDetail?id=" + e.currentTarget.dataset.item.id
            });
        } else {
            wx.navigateTo({
                url: "/grass/pages/grassVideo/grassVideo?id=" + e.currentTarget.dataset.item.id
            });
        }
    },
    /**
  * 轮播切换
  */
    swiperChange(e) {
        console.log(e);
        this.setData({
            current: e.detail.current
        });
    },
    //跳转页面
    goToPages(e) {
        var that = this;
        common.getUserInfoNew({
            success() {
                customLink(e.detail.itemData);
            }
        });
    },
    goToDetail(e) {
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    //图片加载完实现瀑布流 -无法实现 （图片加载不全）
    imgLoad: function(e) {
        console.log("index" + e.target.dataset.index);
        let beforeWidth = e.detail.width;
        //图片原始宽度 
                let beforeHeight = e.detail.height;
        //图片原始高度
                let nowWidth = this.data.imgWidth;
        //图片设置的宽度
        //比例=图片原始宽度/图片设置的宽度
                let wProportion = beforeWidth / nowWidth;
        //图片设置的高度=图片原始高度/比例
                let imgHeight = beforeHeight / wProportion;
        //当左区域高=右区域高   或   当左区域高<右区域高
                if (this.data.lHeight == this.data.rHeight || this.data.lHeight < this.data.rHeight) {
            grassrighttList.push(e.target.dataset.item);
            this.setData({
                lHeight: this.data.lHeight + imgHeight
            });
            //当左区域高>右区域高
                } else if (this.data.lHeight > this.data.rHeight) {
            grassLeftList.push(e.target.dataset.item);
            this.setData({
                rHeight: this.data.rHeight + imgHeight
            });
        }
        //当完成最后一次分组        
                if (e.target.dataset.index == this.data.grassList.length - 1) {
            this.setData({
                grassLeftList: grassLeftList,
                grassrighttList: grassrighttList,
                grassList: []
            });
        }
    },
    touchStart(e) {
        console.log(e);
        this.setData({
            "touch.x": e.changedTouches[0].clientX,
            "touch.y": e.changedTouches[0].clientY
        });
    },
    touchEnd(e) {
        let that = this;
        let x = e.changedTouches[0].clientX;
        let y = e.changedTouches[0].clientY;
        var direction = util.getTouchData(x, y, that.data.touch.x, that.data.touch.y);
    },
    chooseClass: common.throttle(function(e) {
        let that = this;
        if (that.data.hasMore) {
            that.setData({
                hasMore: false
            });
            that.setData({
                classIndex: e[0].currentTarget.dataset.idx,
                chooseClass: e[0].currentTarget.dataset.id,
                page: 1,
                grassList: []
            });
            that.getNewGrass();
        }
    }, 1e3),
    chooseTopic: function(e) {
        let that = this;
        // that.setData({
        //   grassList:[],
        //   chooseTopic: e.currentTarget.dataset.id,
        //   page: 1
        // })
        // that.getNewGrass();
                wx.navigateTo({
            url: "/grass/pages/grassTopics/grassTopics?info=" + JSON.stringify(e.currentTarget.dataset.item)
        });
    },
    getTopicList: function() {
        let that = this;
        common.request({
            endpoint: "Plantgrass/manage/grass_topic",
            method: "post",
            data: {
                do: "topic"
            },
            success: res => {
                that.setData({
                    topicList: res.extra
                });
                that.dealTopList();
            }
        });
    },
    /**
  * 上传显示奖励规则
  */
    ruleModalShow: function() {
        let that = this;
        if (that.data.plantgrass.paid_status == 1) {
            common.getUserInfoNew({
                success() {
                    that.setData({
                        ruleModal: true
                    });
                }
            });
        } else {
            wx.showModal({
                title: "提示",
                content: "必须购买商品才能上传种草！",
                showCancel: false
            });
        }
    },
    ruleModalHide: function() {
        let that = this;
        that.setData({
            ruleModal: false
        });
    }
});